package com.wanpinghui.supplier.addrbook;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;

import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.adapter.AddressBooksAdapter;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.addrbook.AddrbookService;
import com.wanpinghui.wphlibrary.model.addrbook.bean.MobileListBean;
import com.wanpinghui.wphlibrary.model.addrbook.bean.MoblieBean;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.yunshl.yunshllibrary.recyclerview.BaseRecyclerViewAdapter;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit.callback.YRequestCallback;

/**
 * 功能描述
 * author:caitiangui
 * time:2018/1/8
 */
@ContentView(R.layout.layout_activity_add_addrbook)
public class AddAddrBookFriendsActivity extends BaseActivity {

    @ViewInject(R.id.ll_empty_view)
    private LinearLayout ll_empty_view;

    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser tpl_title;

    @ViewInject(R.id.ll_tv_null)
    private LinearLayout ll_tv_null;

    private AddressBooksAdapter adapter;

    @ViewInject(R.id.recyclerview)
    private SuperRecyclerView recyclerView;
    private List<MoblieBean> moblieBeanList;

    private List<MoblieBean> localContactList;

    private int currpage = 1;

    private ArrayList<HashMap<String, String>> readContact;
    private List<String> stringList;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        String user_phone = "";
        if (UserInfoUtil.getUserInfo() != null) {
            UserInformation userInformation = UserInfoUtil.getUserInfo().getUser();
            user_phone = userInformation.getMobile();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                ll_empty_view.setVisibility(View.VISIBLE);
            } else {
                readContact(user_phone);
                ll_empty_view.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            }
        } else {
            readContact(user_phone);
            ll_empty_view.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddressBooksAdapter(this);
        adapter.setNewFriends(true);
        recyclerView.setAdapter(adapter);
        mobil_list(currpage, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH);
    }

    private void readContact(final String user_phone) {
        WPHSdk.getService(AddrbookService.class).readContact(AddAddrBookFriendsActivity.this, new YRequestCallback<ArrayList<HashMap<String, String>>>() {
            @Override
            public void onSuccess(ArrayList<HashMap<String, String>> var1) {
                readContact = var1;
                stringList = new ArrayList<>();
                localContactList = new ArrayList<>();
                for (int i = 0; i < readContact.size(); i++) {
                    String local_phone = readContact.get(i).get("phone");
                    if (local_phone != null && !local_phone.equals(user_phone)) {
                        MoblieBean moblieBean = new MoblieBean();
                        moblieBean.setNickname(readContact.get(i).get("name"));
                        moblieBean.setMobile(local_phone);
                        moblieBean.setState(10);
                        localContactList.add(moblieBean);
                        stringList.add(local_phone);
                    }
                }
                currpage=1;
                updateMobilList(stringList);
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {

            }
        });
    }

    @Override
    public void bindEvents() {
        tpl_title.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.tv_open_addrbook).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(AddAddrBookFriendsActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
                    ActivityCompat.requestPermissions(AddAddrBookFriendsActivity.this, new String[]{android.Manifest.permission.READ_CONTACTS}, 1);
            }
        });
//        SwipeRefreshLayout.OnRefreshListener refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                currpage = 1;
//                mobil_list(currpage, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH);
//            }
//        };
//        recyclerView.setRefreshListener(refreshListener);
        adapter.setListener(new AddressBooksAdapter.setOnItemListener() {
            @Override
            public void setAddFriend(int position) {
                final MoblieBean bean = adapter.getDatas().get(position);
                WPHSdk.getService(AddrbookService.class).addFriends(bean.getFollowed_id(), new YRequestCallback<Object>() {
                    @Override
                    public void onSuccess(Object var1) {
                        bean.setState(30);
                        bean.setStatus_display("等待认证");
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText("添加失败");

                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();

                    }
                });
            }

            @Override
            public void setAgreeFriend(int position) {
                final MoblieBean bean = adapter.getDatas().get(position);
                WPHSdk.getService(AddrbookService.class).agreeAddFriendsLogs(bean.getId_(), new YRequestCallback<MobileListBean>() {
                    @Override
                    public void onSuccess(MobileListBean var1) {
//                        bean.setState(30);
//                        bean.setStatus_display("已邀请");
//                        adapter.notifyDataSetChanged();
//                      //  showWarningText("邀请成功");
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText(message);

                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();
                    }
                });
            }

            @Override
            public void setInvite(int position) {
                final MoblieBean bean = adapter.getDatas().get(position);
                WPHSdk.getService(AddrbookService.class).inviteFriends(bean.getMobile(), bean.getNickname(), new YRequestCallback<Object>() {
                    @Override
                    public void onSuccess(Object var1) {
                        bean.setState(30);
                        bean.setStatus_display("已邀请");
                        adapter.notifyDataSetChanged();
                        showWarningText("邀请成功");
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText(message);

                    }

                    @Override
                    public void onException(Throwable var1) {

                    }
                });
                // showWarningText("暂时不可以邀请");
            }
        });

    }

    //更新上传通讯录
    private void updateMobilList(List<String> stringList) {
        if (stringList == null) return;
        if (stringList.size() == 0) return;
        WPHSdk.getService(AddrbookService.class).updateMobilList(stringList, new YRequestCallback<Object>() {
            @Override
            public void onSuccess(Object var1) {
                //    LogUtils.d("onSuccess",var1.toString());
                mobil_list(currpage, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH);
            }

            @Override
            public void onFailed(int var1, String message) {
                //    LogUtils.d("onFailed",message);
            }

            @Override
            public void onException(Throwable var1) {
                //      LogUtils.d("onException",var1.toString());
            }
        });
    }

    private void mobil_list(int page, final int type) {
        //"page_type": 10    // 10 可能认识   20 通讯录(包括已邀请)
        WPHSdk.getService(AddrbookService.class).mobil_list(page, 20, 20, new YRequestCallback<MobileListBean>() {
            @Override
            public void onSuccess(MobileListBean var1) {

                if (type == BaseRecyclerViewAdapter.TYPE_PULL_REFRESH) {
                    moblieBeanList = var1.getList();
                    if (moblieBeanList != null && moblieBeanList.size() > 0) {

                        for (int i = 0; i < localContactList.size(); i++) {

                            if (!moblieBeanList.contains(localContactList.get(i))) {

                                moblieBeanList.add(localContactList.get(i));
                            }  else {

                            }

                        }

                    } else {
                        moblieBeanList.addAll(localContactList);
                    }
                }
                adapter.setDatas(moblieBeanList);
                if (adapter.getItemCount() == 0) {
                    recyclerView.setVisibility(View.GONE);
                    ll_tv_null.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailed(int var1, String message) {

                //     ll_tv_null.setVisibility(View.VISIBLE);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });

    }

    @Override
    public void initData() {

    }
}
